<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <div>
          <el-button
            type="primary"
            size="default"
            icon="ele-Plus"
            @click="emit('cutSpuComponent', 2)"
            :disabled="!category3Id"
            >添加SPU</el-button
          >
        </div>
      </template>
      <el-table border stripe :data="spuList">
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="SPU名称" prop="spuName"> </el-table-column>
        <el-table-column label="描述" prop="description"> </el-table-column>
        <el-table-column label="操作" width="248">
          <template v-slot="{ row }">
            <div>
              <el-button type="primary" size="small" icon="ele-Plus" />
              <el-button
                type="warning"
                size="small"
                icon="ele-Edit"
                @click="emit('cutSpuComponent', 2, row)"
              />
              <el-button type="info" size="small" icon="ele-Warning" />
              <el-button type="danger" size="small" icon="ele-Delete" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        layout="  prev, pager, next,sizes,total"
        :total="total"
        :style="{ marginTop: '20px' }"
      />
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuList",
});
</script>

<script setup lang="ts">
import { reqGetSpuList, type spuItemType, type spuListType } from "@/api/spu";
import useCategoryStore from "@/stores/category";
import { storeToRefs } from "pinia";
import { onMounted, ref, watch } from "vue";
const currentPage = ref(1); //当前页
const pageSize = ref(3); //每页展示条数
const total = ref(0); // 总体数

// categoryStore对象
const categoryStore = useCategoryStore();

// 获取store对象中数据
const { category3Id } = storeToRefs(categoryStore);

// spuList 数据

const spuList = ref<spuListType>([]);

// 获取自定义事件
const emit = defineEmits<{
  (event: "cutSpuComponent", showIndex: number, row?: spuItemType): void;
}>();

// 初始化获取SPU列表数据方法
const getSpuList = async () => {
  const result = await reqGetSpuList(
    currentPage.value,
    pageSize.value,
    category3Id.value as number
  );
  spuList.value = result.records;
  total.value = result.total;
};

// 监听category3Id  变化发送初始化数据请求
watch(category3Id, () => {
  // 如果category3Id 为空则清除数据
  if (!category3Id.value) {
    spuList.value = [];
    return;
  }
  console.log(1);
  getSpuList();
});

// 监听页码数据发生变化 重新请求数据
watch([currentPage, pageSize], () => {
  getSpuList();
});

// 初始化判断是否有category3Id 如果有则请求数据
onMounted(() => {
  if (category3Id.value) getSpuList();
});
</script>

<style scoped lang="scss"></style>
